package com.running.base.run.aspect;

import com.running.base.run.exception.BizException;
import com.running.base.run.exception.enums.CommonEnum;
import com.running.base.run.params.base.ResultBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;


@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Value("${server.manager}")
    private String server_manager;


    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResultBody bizExceptionHandler(BizException e) {
        logger.error("发生业务异常！原因是:", e);
        return ResultBody.error(e.getErrorCode(),e.getErrorMsg());
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultBody methodArgumentExceptionHandler(Exception e) {
        logger.error("参数校验异常！原因是:", e);
        return ResultBody.error(CommonEnum.PARAM_NOT_MATCH);
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultBody exceptionHandler(Exception e) {
        logger.error("未知异常！原因是:", e);
        return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseBody
    public ResultBody exceptionUrlHandler(Exception e) {
        logger.error("未知异常！原因是:", e);
        return ResultBody.error(CommonEnum.URL_EXCEPTION);
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ResultBody exceptionHandlerUrl(Exception e) {
        logger.error("请求url method error！原因是:", e);
        if (e.getMessage().contains("POST")) {
            return ResultBody.error(CommonEnum.URL_POST_EXCEPTION);
        } else if (e.getMessage().contains("GET")) {
            return ResultBody.error(CommonEnum.URL_GET_EXCEPTION);
        } else {
            return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
        }

    }
}
